# WiFi自动断联脚本
# 5分钟循环：前2分钟等待，后3分钟断联网操作
#Requires -RunAsAdministrator

param(
    [int]$WaitMinutes = 2,              # 每个循环开始的等待时间（分钟）
    [int]$DisconnectSeconds = 10,       # 每次断网时长（秒）
    [int]$ConnectSeconds = 10,          # 每次联网时长（秒）
    [int]$OperationMinutes = 3,         # 断联网操作持续时间（分钟）
    [int]$TotalCycles = 0               # 总循环次数（0表示无限循环）
)

Write-Host "WiFi自动断联脚本" -ForegroundColor Cyan
Write-Host "=================" -ForegroundColor Cyan
Write-Host "循环配置：" -ForegroundColor Yellow
Write-Host "  等待时间: $WaitMinutes 分钟" -ForegroundColor Gray
Write-Host "  操作时间: $OperationMinutes 分钟" -ForegroundColor Gray
Write-Host "  断网时长: $DisconnectSeconds 秒" -ForegroundColor Gray
Write-Host "  联网时长: $ConnectSeconds 秒" -ForegroundColor Gray
Write-Host "  总循环时间: $($WaitMinutes + $OperationMinutes) 分钟" -ForegroundColor Gray
Write-Host "  循环次数: $(if($TotalCycles -eq 0){'无限'}else{$TotalCycles})" -ForegroundColor Gray
Write-Host ""

# 获取WiFi适配器
function Get-WiFiAdapter {
    $adapter = Get-NetAdapter | Where-Object { 
        $_.InterfaceDescription -like "*Wi-Fi*" -or 
        $_.InterfaceDescription -like "*Wireless*" -or 
        $_.InterfaceDescription -like "*802.11*" -or
        $_.Name -eq "WLAN" -or 
        $_.Name -eq "Wi-Fi" 
    } | Select-Object -First 1
    
    if (-not $adapter) {
        throw "未找到WiFi适配器！"
    }
    
    return $adapter
}

# 断开WiFi
function Disconnect-WiFi {
    param($adapter)
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] 断开WiFi: $($adapter.Name)" -ForegroundColor Red
    Disable-NetAdapter -Name $adapter.Name -Confirm:$false -ErrorAction Stop
}

# 连接WiFi
function Connect-WiFi {
    param($adapter)
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] 连接WiFi: $($adapter.Name)" -ForegroundColor Green
    Enable-NetAdapter -Name $adapter.Name -Confirm:$false -ErrorAction Stop
}

# 显示倒计时
function Show-Countdown {
    param(
        [int]$seconds,
        [string]$message,
        [ConsoleColor]$color = "Gray"
    )
    
    for ($i = $seconds; $i -gt 0; $i--) {
        Write-Host -NoNewline "`r$message $i 秒  " -ForegroundColor $color
        Start-Sleep -Seconds 1
    }
    Write-Host "`r$message 完成！          " -ForegroundColor $color
}

# 执行断联网操作
function Perform-DisconnectConnectOperations {
    param(
        $adapter,
        [int]$durationMinutes,
        [int]$disconnectSeconds,
        [int]$connectSeconds
    )
    
    $operationStartTime = Get-Date
    $operationEndTime = $operationStartTime.AddMinutes($durationMinutes)
    $operationCount = 0
    
    Write-Host ""
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] 开始断联网操作，持续 $durationMinutes 分钟" -ForegroundColor Yellow
    Write-Host ""
    
    while ((Get-Date) -lt $operationEndTime) {
        $operationCount++
        $remainingTime = $operationEndTime - (Get-Date)
        
        # 检查剩余时间是否足够完成一次完整的断联操作
        if ($remainingTime.TotalSeconds -lt ($disconnectSeconds + 2)) {
            Write-Host "剩余时间不足，结束操作" -ForegroundColor Gray
            break
        }
        
        Write-Host "--- 操作 #$operationCount [剩余: $([Math]::Floor($remainingTime.TotalSeconds))秒] ---" -ForegroundColor Cyan
        
        # 断网
        try {
            Disconnect-WiFi -adapter $adapter
            Show-Countdown -seconds $disconnectSeconds -message "断网中，剩余" -color Red
        } catch {
            Write-Host "断网失败: $_" -ForegroundColor Red
        }
        
        # 检查是否还有时间继续
        if ((Get-Date) -ge $operationEndTime) {
            break
        }
        
        # 联网
        try {
            Connect-WiFi -adapter $adapter
            
            # 计算联网时间（确保不超过结束时间）
            $remainingSeconds = ($operationEndTime - (Get-Date)).TotalSeconds
            if ($remainingSeconds -gt $connectSeconds) {
                Show-Countdown -seconds $connectSeconds -message "联网中，剩余" -color Green
            } elseif ($remainingSeconds -gt 0) {
                Show-Countdown -seconds ([Math]::Floor($remainingSeconds)) -message "联网中，剩余" -color Green
            }
        } catch {
            Write-Host "联网失败: $_" -ForegroundColor Red
        }
        
        Write-Host ""
    }
    
    # 确保最后是联网状态
    try {
        Connect-WiFi -adapter $adapter | Out-Null
    } catch {}
    
    return $operationCount
}

# 主程序
try {
    # 获取WiFi适配器
    $wifiAdapter = Get-WiFiAdapter
    Write-Host "检测到WiFi适配器: $($wifiAdapter.Name)" -ForegroundColor Green
    Write-Host "描述: $($wifiAdapter.InterfaceDescription)" -ForegroundColor Gray
    Write-Host ""
    Write-Host "按 Ctrl+C 可随时停止脚本" -ForegroundColor Yellow
    Write-Host ""
    
    # 主循环
    $cycleCount = 0
    $totalOperations = 0
    $scriptStartTime = Get-Date
    
    while ($TotalCycles -eq 0 -or $cycleCount -lt $TotalCycles) {
        $cycleCount++
        $cycleStartTime = Get-Date
        
        Write-Host ("=" * 70) -ForegroundColor DarkCyan
        Write-Host "第 $cycleCount 个循环开始 [$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')]" -ForegroundColor Yellow
        Write-Host ("=" * 70) -ForegroundColor DarkCyan
        
        # 阶段1：等待
        Write-Host ""
        Write-Host "[阶段1] 等待 $WaitMinutes 分钟..." -ForegroundColor Cyan
        
        $waitSeconds = $WaitMinutes * 60
        for ($i = $waitSeconds; $i -gt 0; $i--) {
            $minutes = [Math]::Floor($i / 60)
            $seconds = $i % 60
            Write-Progress -Activity "等待中" `
                          -Status "剩余时间: ${minutes}分${seconds}秒" `
                          -PercentComplete ((($waitSeconds - $i) / $waitSeconds) * 100)
            Start-Sleep -Seconds 1
        }
        Write-Progress -Activity "等待中" -Completed
        
        # 阶段2：断联网操作
        Write-Host ""
        Write-Host "[阶段2] 执行断联网操作..." -ForegroundColor Cyan
        
        $operations = Perform-DisconnectConnectOperations `
            -adapter $wifiAdapter `
            -durationMinutes $OperationMinutes `
            -disconnectSeconds $DisconnectSeconds `
            -connectSeconds $ConnectSeconds
        
        $totalOperations += $operations
        
        # 循环完成
        $cycleEndTime = Get-Date
        $cycleDuration = $cycleEndTime - $cycleStartTime
        
        Write-Host ""
        Write-Host ("=" * 70) -ForegroundColor DarkCyan
        Write-Host "第 $cycleCount 个循环完成" -ForegroundColor Green
        Write-Host "循环用时: $([Math]::Floor($cycleDuration.TotalMinutes))分$([Math]::Floor($cycleDuration.Seconds))秒" -ForegroundColor Gray
        Write-Host "本循环断联操作: $operations 次" -ForegroundColor Gray
        Write-Host ("=" * 70) -ForegroundColor DarkCyan
        Write-Host ""
        
        # 如果还有下一个循环，显示提示
        if ($TotalCycles -eq 0 -or $cycleCount -lt $TotalCycles) {
            Write-Host "准备开始下一个循环..." -ForegroundColor Gray
            Write-Host ""
        }
    }
    
    # 脚本完成统计
    $totalDuration = (Get-Date) - $scriptStartTime
    Write-Host ""
    Write-Host ("=" * 70) -ForegroundColor Cyan
    Write-Host "脚本执行完成！" -ForegroundColor Green
    Write-Host ("=" * 70) -ForegroundColor Cyan
    Write-Host "统计信息：" -ForegroundColor Yellow
    Write-Host "  总执行时间: $([Math]::Floor($totalDuration.TotalMinutes))分$([Math]::Floor($totalDuration.Seconds))秒" -ForegroundColor Gray
    Write-Host "  完成循环数: $cycleCount" -ForegroundColor Gray
    Write-Host "  断联操作总数: $totalOperations" -ForegroundColor Gray
    Write-Host ("=" * 70) -ForegroundColor Cyan
    
} catch {
    Write-Host ""
    Write-Host ""
    if ($_ -match "用户|中断") {
        Write-Host "用户中断执行" -ForegroundColor Yellow
    } else {
        Write-Host "发生错误: $_" -ForegroundColor Red
    }
    
    # 确保WiFi恢复连接
    Write-Host ""
    Write-Host "正在恢复WiFi连接..." -ForegroundColor Cyan
    try {
        $adapter = Get-WiFiAdapter
        Enable-NetAdapter -Name $adapter.Name -Confirm:$false -ErrorAction SilentlyContinue
        Write-Host "WiFi已恢复" -ForegroundColor Green
    } catch {
        Write-Host "恢复WiFi失败，请手动检查网络连接" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "按任意键退出..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")